<template>
	<div class="collected_course_container">
		<div class="list" v-loading="loading">
			<template v-if="tableListData.length > 0">
				<study-course v-for="(item, index) in tableListData" :key="index" :data="item">
					<el-button size="small" type="primary" @click="handleStartStudy(item)">开始学习</el-button>
					<el-button size="small" type="danger" @click="handleDeleteData(item)">取消收藏</el-button>
				</study-course>
			</template>
			<el-empty v-else :image-size="150" description="暂无数据"></el-empty>
		</div>
		<div class="page" v-if="dataCount > 0">
			<sw-pagination
				v-bind="pageLayout"
				:total="dataCount"
				:page.sync="queryData.page"
				:limit.sync="queryData.limit"
				@change="queryTableData()"
			></sw-pagination>
		</div>
	</div>
</template>

<script>
import lodash from 'lodash';
import { mapGetters } from 'vuex';
import listMixins from '@/mixins/listMixins';
import studyCourse from '@/views/common/studyItem';
import { getChapterList } from '@/api/course/sysCourseChapter';
import { queryCollectList, deleteCollect } from '@/api/front/myCollectInfo';
export default {
	mixins: [listMixins],
	components: { studyCourse },
	data() {
		return {
			pageName: '课程',
			handName: '取消收藏'
		};
	},
	computed: {
		...mapGetters(['userInfo']),
		userId() {
			return this.userInfo.id;
		},
		listFunction() {
			return eval(queryCollectList);
		},
		deleteFunction() {
			return eval(deleteCollect);
		},
		pageLayout() {
			if (this.isMobile) {
				return { isSizes: false, isJumper: false, layout: 'prev, pager, next' };
			} else {
				return { isSizes: true, isJumper: true, layout: '' };
			}
		},
		tableListData() {
			return this.tableData.map((item) => {
				return { ...item, courseId: item.resId, sysCourseInfo: JSON.parse(item.extFiled) };
			});
		}
	},
	methods: {
		//开始学习
		async handleStartStudy(item) {
			let params = { pid: 0, courseId: item.resId };
			let path = `/front/trainingResources/${item.resId}`;
			let result = await getChapterList(params).then((res) => res.data);
			if (result.code === '0') {
				let datas = result.data || [];
				let chapters = this.$treeAddedSort(datas, 'childList');
				let chapterArr = this.$treeToFlat(chapters, 'childList');
				let chapterNodes = chapterArr.filter((n) => n.type === '2');
				let sortNodes = lodash.orderBy(chapterNodes, ['sort'], ['asc']);
				let juageParams = { courseId: item.resId, nodes: sortNodes };
				let unfinish = await this.$store.dispatch('getUnlearnChapter', juageParams);
				if (juageParams.nodes.length === 0) {
					this.$message.warning('该课程尚未搭建课程章节，请联系管理员添加！');
				} else if (lodash.isEmpty(unfinish)) {
					this.$router.push({ path, query: { type: 'exam' } });
				} else {
					let drama = unfinish.id;
					this.$router.push({ path, query: { type: 'learn', drama } });
				}
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.collected_course_container .page {
	padding: 16px;
}
</style>
